In this article, we will learn how to use the String.Format function to format a string into Decimal number format.
How to format a Double in C# using String.Format
For example, if you have to format a number up to two decimal places, use a pattern that specifies two zeros after point such as 0.00. If a number has fewer decimal places, the rest of the digits are on the right side will be replaced by zeros. If it has more decimal places, the number will be rounded.
Console.Write(String.Format("{0:0.00}", 123.456789)); Console.Write(String.Format("{0:0.00}", 12345.6)); Console.Write(String.Format("{0:0.00}", 123456));
Output
123.46
12345.60
123456.00
The pattern we used above is called the custom format. In C#, we have a few types of custom formats which we can to format the numbers, Such as zero placeholder – {0:00.00}, or digit placeholder {0:(#).##}, or percentage {0:0%}
Add Digits before decimal point using String.Format
If you want a specific number of digits before the decimal point, use zeros N-times before the decimal point.
For example. the code below ensures that there will always be three digits before the decimal point.
Console.Write(String.Format("{0:000.0}", 123.456)); Console.Write(String.Format("{0:000.0}", 12.3456)); Console.Write(String.Format("{0:000.0}", 1.23456)); Console.Write(String.Format("{0:000.0}", -1.23456));
Output
123.5
012.3
001.2
-001.2
Removing leading zero using String.Format
To format a decimal number without a leading zero, simply use # before the decimal point in your custom format.
Console.Write(String.Format("{0:00.00}", 0.12)); // with leading zero Console.Write(String.Format("{0:00.#}", 0.12)); // without leading zero
Output
0.12
.12
Adding thousands separator using String.Format
Use zero and comma separator if you need to format a number to the string while placing the thousands separator.
Console.Write(String.Format("{0:0,0.0}", 10000.00));
Output
10,000.0
Adding parenthesizes to negative Decimal using String.Format
The semicolon operator is used to create a custom formatting which separates positive, negative numbers and zeros.
String.Format("{0:0.00;minus 0.00;zero}", -123.45); String.Format("{0: #, ##0.00; (#,##0.00)} ", -123.45);
Output
minus 123.45
(123.45)
Comments